package com.sayice.coursetable.logic.network;

import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 成绩相关服务
 */
public abstract class ScoreService {
    private static final String SCORE_URL = "http://jwgl.csuft.edu.cn/jsxsd/kscj/cjcx_list";

    /**
     * 获取成绩页面（Jsoup Document）
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回 Jsoup 解析页面后得到的 Document对象，若获取失败则返回 null
     */
    public static Document getScorePage(String username, String password) {
        String scoreHtml = LoginService.loginAndRequestHtml(username, password, httpClient -> {
            String html = null;
            Request courseRequest = new Request.Builder().url(SCORE_URL).get().build();
            try (Response scoreResponse = httpClient.newCall(courseRequest).execute()) {
                String body = Objects.requireNonNull(scoreResponse.body()).string();
                Elements scoreElements = Jsoup.parse(body).select(
                        "table[id=dataList]");
                if (scoreElements.size() != 0) {
                    html = scoreElements.get(0).outerHtml();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return html;
        });
        Log.d("ScoreService", "scoreHtml: " + scoreHtml);
        return scoreHtml == null ? null : Jsoup.parseBodyFragment(scoreHtml);
    }
}
